//
//  WLOAuthViewController.swift
//  WLWeibo
//
//  Created by Devil on 16/8/12.
//  Copyright © 2016年 Wiliam. All rights reserved.
//

import UIKit
import SVProgressHUD


class WLOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        
        guard let url = NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        
        webView.delegate = self


        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
    }
    
//    lazy var webview:UIWebView = UIWebView()
   
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    //取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    //自动填充
    @objc private func autonfillAction(){
    
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    //设置视图
    private func setupUI(){
    
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        
    }
    //设置导航
    private func setupNav(){
    
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autonfillAction")
        navigationItem.title = "微博登录"
    
    }
    
    private lazy var webView: UIWebView = UIWebView()
    
    

}

extension WLOAuthViewController: UIWebViewDelegate {
    //监听webView
    func webView(webView: UIWebView,shouldStartLoadWithRequest request: NSURLRequest,navigationType: UIWebViewNavigationType) -> Bool{
    
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
        
            if let query = request.URL?.query{
            
                let code = query.substringFromIndex("code=".endIndex)
                
                print("\(code)")
                
                WLUserAccountViewModel.sharedTools.getUserAccount(code,finish: {(isSuccess) -> () in
                
                    if !isSuccess{
                    
                        print("请求失败")
                        return
                    }
                    print("请求成功")
                    
                    self.dismissViewControllerAnimated(false, completion: { ()-> Void in
                        
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                        
                        
                    })
                
                })
                return false
                
            
            }
        
        }
        
        return true
    
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }

}

//extension WLOAuthViewController{
//
//    func getUserAccount(code: String){
//        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let params = [
//            "client_id":WBAppKey,
//            "client_secret": WBAppSecret,
//            "grant_type":"authorization_code",
//            "code":code,
//            "redirect_uri": WBRedirect_uri
//        ]
//        
//        let manager = AFHTTPSessionManager()
//        
//        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
//            print("请求成功:\(response)")
//            
//            guard let res = response as? [String: AnyObject] else{
//                return
//            }
//            
//            let userAccount = WLuserAccountModel(dict: res)
//            print(userAccount)
//            
//        }) { (_, error) -> Void in
//            print("请求失败:\(error)")
//        }
// 
//    
//    }
//
//}
















































